﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.IO;

namespace XMK.Tadong.OfficeToSwf
{
    public class BkExecer
    {
        //维护一个前进前出的队列。 
        private Queue m_BkExecItemList;
        private string m_strPDFAndSWFRootPath = "";
        public int BkExecItemCount()
        {
            return m_BkExecItemList.Count;
        }
        private static object lockHelper = new object();
        private System.Web.HttpContext m_HttpContext;
        /// <summary>
        /// 运行状态：true 正在转换 false 转换结束或没开始
        /// </summary>
        private bool m_RunStatus;
        /// <summary>
        /// 上次杀死进程时间
        /// </summary>
        private DateTime m_ProKillProcesTime;

        public BkExecer(System.Web.HttpContext curHttp )
        {
            m_RunStatus = false;
            m_HttpContext = curHttp;
            m_BkExecItemList = new Queue(BkExecManager.BkBufSize);
            m_ProKillProcesTime = DateTime.Now;
            m_strPDFAndSWFRootPath = m_HttpContext.Request.PhysicalApplicationPath + "DataFile\\";

        }
        private void InitData()
        {
            
        }

        /// <summary>
        /// 把表数据转换为执行对象
        /// </summary>
        /// <param name="dr">文件表行对象</param>
        /// <returns></returns>
        public ExecItem GetExecItem(DataRow dr)
        {
            #region
            string strSave_FileName = dr["save_filename"].ToString();
            string strUploadPath = dr["uploadpath"].ToString();
            string strRelativePath = dr["relativepath"].ToString();
            string strSuffix = GetSuffix(strSave_FileName);
            string strFileName = strSave_FileName.Substring(0, 14) + Guid.NewGuid().ToString();//格式：时间+随机数
            int iID = Convert.ToInt32(dr["id"].ToString());
            string strOfficeFilePath = strUploadPath + strRelativePath + strSave_FileName;
            ExecItem ei = new ExecItem(iID, strOfficeFilePath);
            ei.SourceFileSuffix = strSuffix.ToUpper();
            ei.UpLoadPath = m_strPDFAndSWFRootPath;
            if (ei.SourceFileSuffix == "PDF")// || ei.SourceFileSuffix == "GIF" || ei.SourceFileSuffix == "JPG" || ei.SourceFileSuffix == "PNG")
            {
                ei.PDFFilePath = strOfficeFilePath;
            }
            else
            {
                ei.PDFFilePath = ei.UpLoadPath + "PDF" + strRelativePath + strFileName + ".pdf";
            }
            ei.SWFFilePath = ei.UpLoadPath + "SWF" + strRelativePath + strFileName + ".swf";

            return ei;
            #endregion
        }
        /// <summary>
        ///删除文件对应的pdf和swf文件
        /// </summary>
        /// <param name="drFile">文件表行记录</param>
        /// <returns></returns>
        private bool DeletePDFAndSWFFile(DataRow drFile)
        {
            #region 
            bool bOK = true;
            try
            {
                if (drFile["pdffilepath"] != DBNull.Value && drFile["pdffilepath"].ToString() != "" &&
                    drFile["pdffilepath"].ToString() != "1" && drFile["pdffilepath"].ToString() != "0")
                {
                    try
                    {
                        string strPDF = m_strPDFAndSWFRootPath + drFile["pdffilepath"].ToString();
                        if (File.Exists(strPDF))
                        {
                            File.Delete(strPDF);
                        }
                    }
                    catch {
                        bOK = false;
                    }
                }
                if (drFile["swffilepath"] != DBNull.Value && drFile["swffilepath"].ToString() != "" &&
                    drFile["swffilepath"].ToString() != "1" && drFile["swffilepath"].ToString() != "0")
                {
                    try
                    {
                        string strSWF = m_strPDFAndSWFRootPath + drFile["swffilepath"].ToString();
                        if (File.Exists(strSWF))
                        {
                            File.Delete(strSWF);
                        }
                    }
                    catch {
                        bOK = false;
                    }
                }
            }
            catch 
            {
                bOK = false;
            }
            return bOK;
            #endregion
        }
        /// <summary>
        /// 删除pdf和swf记录值
        /// </summary>
        /// <param name="drFile">文件表行记录</param>
        private void DeletePDFAndSWFFileVaule(DataRow drFile)
        {
            #region 
            try
            {
                drFile["pdffilepath"] = "";
                drFile["swffilepath"] = "";
                drFile.AcceptChanges();
            }
            catch { }
            #endregion
        }

        /// <summary>
        /// 删除pdf和sqf文件以及记录
        /// </summary>
        /// <param name="drFile"></param>
        private void DeletePDFAndSWF(DataRow drFile)
        {
            #region
            DeletePDFAndSWFFile(drFile);
            DeletePDFAndSWFFileVaule(drFile);
            #endregion
        }

        /// <summary>
        /// 单独添加一个执行项到执行队列
        /// </summary>
        /// <param name="ei"></param>
        public void AddBkExecItem(ExecItem ei)
        {
            lock (lockHelper)
            {
                //锁定资源。 
                m_BkExecItemList.Enqueue(ei);
            }
        }

        /// <summary>
        /// 向队列中添加一个记录
        /// </summary>
        /// <param name="ID_NeedFiles_File">文件ID</param>
        public void AddBkExecItem(int ID_NeedFiles_File)
        {
            #region 
            //BusinessService.Common.CommonFuntion.WriteLog(DateTime.Now.ToString() + ":AddBkExecItem:追加之前记录数："+m_BkExecItemList.Count.ToString());
            //DataRow dr= ClassNEEDFILES_FILE.GetOneRow(ID_NeedFiles_File.ToString());
            //if (dr != null)
            //{
            //    string strSave_FileName = dr["save_filename"].ToString();
            //    string strUploadPath = dr["uploadpath"].ToString();
            //    string strRelativePath = dr["relativepath"].ToString();
            //    if (!(string.IsNullOrEmpty(strSave_FileName) || string.IsNullOrEmpty(strUploadPath) || string.IsNullOrEmpty(strRelativePath)))
            //    {
            //        string strSuffix = GetSuffix(strSave_FileName);
            //        if (!string.IsNullOrEmpty( strSuffix))
            //        {
            //            //在此处删除原pdf和swf文件
            //            DeletePDFAndSWF(dr);
            //            ExecItem ei = GetExecItem(dr);
            //            AddBkExecItem(ei);
            //        }
            //    }
                
            //}
            //BusinessService.Common.CommonFuntion.WriteLog(DateTime.Now.ToString() + ":AddBkExecItem:追加之后记录数：" + m_BkExecItemList.Count.ToString());
            #endregion
        }

        public void AddBkExecItem(string InstrSave_FileName, string InstrFileName, string InstrOfficeFilePath, string InUpLoadPath)
        {
            #region

            //string strSave_FileName = "2013.docx";
            //原文件名称
            string strSave_FileName = InstrSave_FileName;
            
            string strSuffix = GetSuffix(strSave_FileName);
            //string strFileName = "20140101" + Guid.NewGuid().ToString();//格式：时间+随机数
            //保存文件名称
            string strFileName = InstrFileName;//格式：时间+随机数
           
            //string strOfficeFilePath = "e:\\temp\\" + strSave_FileName;
            //原文件地址
            string strOfficeFilePath = InstrOfficeFilePath + strSave_FileName;
            ExecItem ei = new ExecItem(0, strOfficeFilePath);
            ei.SourceFileSuffix = strSuffix.ToUpper();
            //ei.UpLoadPath = "e:\\temp\\";
            //加载文件地址
            ei.UpLoadPath = InUpLoadPath;
            if (ei.SourceFileSuffix == "PDF")// || ei.SourceFileSuffix == "GIF" || ei.SourceFileSuffix == "JPG" || ei.SourceFileSuffix == "PNG")
            {
                ei.PDFFilePath = strOfficeFilePath;
            }
            else
            {
                ei.PDFFilePath = ei.UpLoadPath +  strFileName + ".pdf";
            }
            ei.SWFFilePath = ei.UpLoadPath + strFileName + ".swf";

            AddBkExecItem(ei);

            #endregion
        }



        public void DoBkExec(object Msg)
        {
            try
            {
                if (m_RunStatus == false)
                {
                    if (m_BkExecItemList == null || m_BkExecItemList.Count == 0)
                    {
                        InitData();
                    }
                }
                else
                {
                    return;
                }
                ExecItem ei;
                int i = 0;
                while (m_BkExecItemList.Count > 0)
                {
                    ++i;
                    m_RunStatus = true;
                    try
                    {

                        lock (lockHelper)
                        {
                            ei = (ExecItem)m_BkExecItemList.Dequeue();
                        }
                        //执行文件转换，可做成多线程
                        bool bOK = ei.ExecFileConvert();
                        //提供程序关闭office进程的时间
                        System.Threading.Thread.Sleep(BkExecManager.QueueItemDueTime);
                    }
                    catch (Exception ex)
                    {
                    }
                }
                KillProcess();
                m_RunStatus = false;
            }
            catch (Exception ex1)
            {
            }
        }

        /// <summary>
        /// 获得文件后缀名 不包括点
        /// </summary>
        /// <param name="FileName">文件名</param>
        /// <returns></returns>
        private string GetSuffix(string FileName)
        {
            #region
            int iStart = FileName.LastIndexOf(".");
            if (iStart > 0)
            {
                string strSuffix = FileName.Substring(iStart + 1);
                return strSuffix;
            }
            return "";
            #endregion
        }


        /// <summary>
        /// 定时杀死进程
        /// </summary>
        /// <returns></returns>
        private bool KillProcess()
        {
            #region 
            try
            {
                DateTime dt = DateTime.Now;
                TimeSpan ts = dt - m_ProKillProcesTime;
                if (ts.Days >= 1)
                {
                    m_ProKillProcesTime = dt;
                    List<string> lstName = new List<string>();
                    lstName.Add("WINWORD.EXE");
                    lstName.Add("EXCEL.EXE");
                    lstName.Add("POWERPNT.EXE");
                    return ProcessManage.KillProcess(lstName);
                }
                return true;
            }
            catch 
            {
                return false;
            }
            
            #endregion
        }

    } 
}
